from django.shortcuts import render,HttpResponse,redirect
from rbac import models as rbac_model

from serviceinfo import models
from rbac.views import Per
import json
import datetime


def index(request):
    id=request.session.get("user_id")
    user=rbac_model.User.objects.filter(id=id).first()

    titles = []
    # {product: '1月', 'qding': 43.3, 'tyh': 85.8}

    groups = models.Group.objects.all()
    for gg in groups:
        titles.append(gg.name)
    d = datetime.datetime.now()
    days = []
    data = []
    dayss = []
    for i in range(30,-1,-1):
        oneday = datetime.timedelta(days=i)
        day = d - oneday
        dayss.append(day)
        days.append("%s-%s-%s"%(day.year,day.month,day.day))

    for gg in groups:
        ss = dict()
        ss["name"] = gg.name
        ss["type"] = "line"
        ss["data"] = [gg.configuration_set.filter(createDate__year=day.year,createDate__month=day.month,createDate__day=day.day).count() for day in dayss]
        # print(ss)
        data.append(ss)
    # data = [{'name': 'qding', 'type': 'line',
    #   'data': [1, 2, 3, 4, 4, 5, 7, 0, 8, 10, 22, 11, 11, 22, 1, 2, 3, 4, 4, 5, 7, 0, 8, 10, 22, 11, 11, 22, 0, 3, 0]},
    #  {'name': 'tyh', 'type': 'line',
    #   'data': [0, 8, 10, 22, 11, 11, 22, 1, 2, 3, 4, 4, 5, 7, 0, 8, 10, 22, 11, 11, 22, 0, 3, 0, 0, 0, 0, 2,0,0,0]}]

    all_apps = models.Configuration.objects.filter().all()
    # print(data)
    # print(titles)
    # print(days)
    # print(dayss)
    # all_datas = models.Configuration.objects.filter(create_date__day=26)
    # print("cc",all_datas)
    return render(request,"index.html",locals())


def serviceinfo(request):
    id=request.session.get("user_id")
    user = rbac_model.User.objects.filter(id=id).first()
    print(request.actions)
    per = Per(request.actions)

    print("rrrr",request.path)

    # 从URL取参数
    page_num = request.GET.get("page")
    # print(page_num, type(page_num))
    appname = request.GET.get("appname")
    group = request.GET.get("group")
    env = request.GET.get("env")
    if env:
        env = int(env)
    else:
        env = 1

    if appname == None:
        appname = ''
    else:
        appname = appname.strip()

    if group:
        group = int(group)
    else:
        group = 1
    print("app",appname)
    print("app",page_num)
    print("app",group)

    envs = models.Configuration.env_type_choices
    # envs = [('dev',),('qa',),('online',),('all',)]
    envs = list(envs)
    envs.append((4, 'all'))
    print("eeee",envs)
    groups = list(models.Group.objects.all().values_list())
    groups.append((100,'all'))
    print("ggg",groups)
    if env == 4 and group == 100:
        # 总数据是多少
        total_count = models.Configuration.objects.filter(sername__sername__contains=appname).all().count()

        from utils.mypage import Page
        page_obj = Page(page_num, total_count, per_page=9,
                        url_prefix="/serviceinfo/?env={}&appname={}&group={}&".format(env,appname,group), max_page=9, )
        ret = models.Configuration.objects.filter(sername__sername__contains=appname).all()[page_obj.start:page_obj.end]
        page_html = page_obj.page_html()
    elif env == 4 and group != 100:
        # 总数据是多少
        total_count = models.Configuration.objects.filter(sername__sername__contains=appname,group_id=group).all().count()

        from utils.mypage import Page
        page_obj = Page(page_num, total_count, per_page=9,
                        url_prefix="/serviceinfo/?env={}&appname={}&group={}&".format(env,appname,group), max_page=9, )
        print(page_obj.start,page_obj.end)
        ret = models.Configuration.objects.filter(sername__sername__contains=appname,group_id=group).all()[page_obj.start:page_obj.end]
        page_html = page_obj.page_html()
    elif env != 4 and group == 100:
        # 总数据是多少
        total_count = models.Configuration.objects.filter(sername__sername__contains=appname,env_type=env).all().count()

        from utils.mypage import Page
        page_obj = Page(page_num, total_count, per_page=9,
                        url_prefix="/serviceinfo/?env={}&appname={}&group={}&".format(env,appname,group), max_page=9, )
        ret = models.Configuration.objects.filter(sername__sername__contains=appname,env_type=env).all()[page_obj.start:page_obj.end]
        page_html = page_obj.page_html()
    else:
        # 总数据是多少
        total_count = models.Configuration.objects.filter(sername__sername__contains=appname,env_type=env,group_id=group).all().count()

        from utils.mypage import Page
        page_obj = Page(page_num, total_count, per_page=9,
                        url_prefix="/serviceinfo/?env={}&appname={}&group={}&".format(env,appname,group), max_page=9, )
        # print(page_num)
        # print(page_obj.start,page_obj.end)
        ret = models.Configuration.objects.filter(sername__sername__contains=appname,env_type=env,group_id=group).all()[page_obj.start:page_obj.end]
        page_html = page_obj.page_html()

    return render(request,"service.html",{"server_list":ret,"page_html":page_html,"user":user,"per":per,"appname":appname,"envs":envs,"env":env,"group":group,"groups":groups})


def service_add(request):
    print("addaddadd")
    id=request.session.get("user_id")

    user=rbac_model.User.objects.filter(id=id).first()
    print("22222222222")
    print(user.department.id)
    print(request.session["menu_permission_list"])
    per=Per(request.actions)
    if request.method == "POST":
        # app_detail_id = request.POST.get("proj_id")
        appname = request.POST.get("proname").strip()
        app_type = request.POST.get("app_type")
        gitaddr = request.POST.get("gitaddr").strip()
        git_releases = request.POST.get("git_releases").strip()
        obj_num = request.POST.get("obj_num")
        optimization = request.POST.get("optimization")
        if int(optimization) == 1:
            optimization_detail = None
        else:
            optimization_detail = request.POST.get("optimization_detail").strip()
        system_version = request.POST.get("system_version")
        java_version = request.POST.get("java_version")
        cpu_capacity = request.POST.get("cpu_capacity")
        mem_capacity = request.POST.get("mem_capacity")
        configcenter = request.POST.get("configcenter")
        configcenter_addr = request.POST.get("configcenter_addr")
        interface_type = request.POST.get("interface_type")

        print("-----",appname,app_type,gitaddr,optimization,optimization_detail,configcenter,configcenter_addr,interface_type)
        print("++++",system_version,cpu_capacity,mem_capacity)

        connserver_info = {"sername":appname,"gitaddr":gitaddr,"git_releases":git_releases}
        print(connserver_info)
        config_info = {"app_type":int(app_type),"optimize_type": int(optimization), "optimize_detail": optimization_detail,
                     "system_release":int(system_version),"java_version": int(java_version),"cpu":int(cpu_capacity),"mem":int(mem_capacity),
                     "configcenter_type": int(configcenter), "configcenter_addr": configcenter_addr,"node_num":int(obj_num),
                     "interface_type": interface_type,"group_id":1,"related_user_id":user.id}

        res = {"status": None}
        sername = models.ConnService.objects.filter(sername=appname)
        if sername:
            print("55555")
            res["status"] = 500
        else:
            print("444444")
            connserver_obj =  models.ConnService.objects.create(**connserver_info)

            config_info.update({"env_type": 1, "sername_id": connserver_obj.id})
            print(config_info)
            models.Configuration.objects.create(**config_info)
            res["status"] = 200

        return HttpResponse(json.dumps(res))

def service_delete(request,id):
    print("id",id)
    res = {"status":None}
    service_obj = models.Configuration.objects.filter(id=int(id))[0]
    sername_id = models.Configuration.objects.filter(id=int(id))[0].sername_id
    # print(sername_id)
    try:
        from serviceinfo.jenkins_report import jenkins_job_del
        # print("zzzzz")
        resinfo = jenkins_job_del(service_obj.sername.sername, service_obj.get_env_type_display(), service_obj.group.name)
        models.Configuration.objects.filter(id=id).delete()
        res["status"] = 200
        config_ids = [conn.id for conn in models.Configuration.objects.filter(sername_id=sername_id)]
        if not config_ids:
            models.ConnService.objects.filter(id=sername_id).delete()
        #     print("finashed???")
        # print("kkkk")

    except Exception as e:
        res["status"] = 500
    # print(res)
    return HttpResponse(json.dumps(res))


def service_edit(request,id):
    print("editeditedit")
    res = {"status":None}
    app_id = request.POST.get("app_id")
    gitaddr = request.POST.get("gitaddr")
    git_releases = request.POST.get("git_releases")
    obj_num = request.POST.get("obj_num")
    optimization = request.POST.get("optimization")
    if int(optimization) == 1:
        optimization_detail = None
    else:
        optimization_detail = request.POST.get("optimization_detail")
    system_version = request.POST.get("system_version")
    java_version = request.POST.get("java_version")
    cpu_capacity = request.POST.get("cpu_capacity")
    mem_capacity = request.POST.get("mem_capacity")
    configcenter = request.POST.get("configcenter")
    configcenter_addr = request.POST.get("configcenter_addr")
    # request_path = request.POST.get("request_path")
    # service_path = request.POST.get("service_path")
    interface_type = request.POST.get("interface_type")
    # interface_types = json.loads(interface_type)
    # config_obj = models.Configuration.objects.get(id=app_id)
    server_obj = models.ConnService.objects.filter(configuration__id=app_id)[0]
    server_obj.gitaddr =gitaddr
    server_obj.git_releases =git_releases
    server_obj.save()
    print("app_id",app_id)
    print("serserser",server_obj)
    try:
        port_config_info = {
            "optimize_type":int(optimization),
            "optimize_detail":optimization_detail,
            "system_release":int(system_version),
            "node_num":int(obj_num),
            "java_version":int(java_version),
            "cpu":int(cpu_capacity),
            "mem":int(mem_capacity),
            "configcenter_type":int(configcenter),
            "configcenter_addr":configcenter_addr,
            "interface_type":interface_type,
        }
        print("portport",port_config_info)
        print(models.Configuration.objects.filter(id=app_id))
        models.Configuration.objects.filter(id=app_id).update(**port_config_info)

        res["status"] = 200
    except Exception as e:
        res["status"] = 500

    # print(optimization_detail,interface_type,port,path)
    return HttpResponse(json.dumps(res))


def service_api(request):
    res = {"status": None, "info": None}
    appname = request.GET.get("appname")
    group = request.GET.get("group")
    env_type = request.GET.get("env")
    # env_typess = models.Configuration.env_type_choices
    env_typess = {"dev":1,"qa":2,"online":3}
    if models.Group.objects.filter(name=group) and models.ConnService.objects.filter(sername=appname):
        projs = models.Configuration.objects.filter(sername__sername=appname.strip(),group__name=group.strip(),env_type=env_typess[env_type])
        if projs:
            conser_obj = projs[0]
            if conser_obj.optimize_type == 1:
                optimize_detail = "-Xms512m -Xmx512m -XX:PermSize=256M -XX:MaxPermSize=256M -Ddruid.registerToSysProperty=true -Dfile.encoding=utf-8"
            else:
                optimize_detail = conser_obj.optimize_detail
            if "http" in conser_obj.interface_type:
                info = {"app_type": conser_obj.get_app_type_display(),
                        "appname": conser_obj.sername.sername,
                        "gitaddr": conser_obj.sername.gitaddr,
                        "git_releases":conser_obj.sername.git_releases.split("\n"),
                        "env_type":conser_obj.get_env_type_display(),
                        "node_num": conser_obj.node_num,
                        "group":conser_obj.group.name,
                        "optimize_detail": optimize_detail,
                        "java_version": conser_obj.java_version,
                        "system_release": conser_obj.get_system_release_display(),
                        "cpu": conser_obj.get_cpu_display(),
                        "mem": conser_obj.get_mem_display(),
                        "configcenter_type": conser_obj.get_configcenter_type_display(),
                        "configcenter_addr": conser_obj.configcenter_addr,
                        "interface_type": conser_obj.interface_type,
                        "http":{"domain":conser_obj.hostname,"port": conser_obj.port,
                                "request_path": conser_obj.request_path,"service_path":conser_obj.service_path,"personalize":conser_obj.get_personalize_display(),"persontext":conser_obj.persontext}}
            else:
                info = {"app_type": conser_obj.get_app_type_display(),
                        "appname": conser_obj.sername.sername,
                        "gitaddr": conser_obj.sername.gitaddr,
                        "git_releases": conser_obj.sername.git_releases.split("\n"),
                        "env_type":conser_obj.get_env_type_display(),
                        "node_num": conser_obj.node_num,
                        "group":conser_obj.group.name,
                        "optimize_detail": optimize_detail,
                        "java_version": conser_obj.java_version,
                        "system_release": conser_obj.get_system_release_display(),
                        "cpu": conser_obj.get_cpu_display(),
                        "mem": conser_obj.get_mem_display(),
                        "configcenter_type": conser_obj.get_configcenter_type_display(),
                        "configcenter_addr": conser_obj.configcenter_addr,
                        "interface_type": conser_obj.interface_type}
            res["info"] = info
            res["status"] = 200
        else:
            res["status"] = 500
            res["info"] = "this env service name not find !"
    else:
        res["status"] = 500
        res["info"] = "service name or group  not find !"
    return HttpResponse(json.dumps(res))



def appinfo(request):
    if request.method == "POST":
        proj_id = int(request.POST.get("proj_id"))
        # sername_env = int(request.POST.get("env_type"))
        print(proj_id)
        # print(sername_env)
        # print("ppp", proj_id)
        conser_obj = models.Configuration.objects.filter(id=proj_id)[0]
        print(11111,conser_obj)
        env_typess = list(models.Configuration.env_type_choices)
        option_typess = models.Configuration.optimize_type_choices
        configcenter_typess = models.Configuration.configcenter_type_choices

        java_versionss = models.Configuration.java_version_choices
        system_releasess = models.Configuration.system_type_choices
        cpuss = models.Configuration.cpu_capacity_choices
        memss = models.Configuration.mem_capacity_choices

        interface_typess = ["http", "dubbo"]
        print(conser_obj)
        proj_info = {"proj_id": conser_obj.id, "app_type": conser_obj.get_app_type_display(),
                     "proname": conser_obj.sername.sername,
                     "gitaddr": conser_obj.sername.gitaddr, "git_env": conser_obj.env_type,
                     "git_releases":conser_obj.sername.git_releases,
                     "optimization": conser_obj.optimize_type,
                     "system_release":conser_obj.system_release,
                     "cpu":conser_obj.cpu,
                     "mem":conser_obj.mem,
                     "hostname":conser_obj.hostname,
                     "node_num":conser_obj.node_num,
                     "optimization_detail": conser_obj.optimize_detail,
                     "java_version": conser_obj.java_version, "configcenter": conser_obj.configcenter_type,
                     "configcenter_addr": conser_obj.configcenter_addr,
                     "port":conser_obj.port,"request_path":conser_obj.request_path,"service_path":conser_obj.service_path,
                     "env_typess": env_typess, "option_typess": option_typess,
                     "configcenter_typess": configcenter_typess,
                     "interface_type": conser_obj.interface_type, "interface_typess": interface_typess,
                     "java_versionss":java_versionss,"system_releasess":system_releasess,"cpuss":cpuss,"memss":memss}
        print("hhhhh",proj_info)

        return HttpResponse(json.dumps(proj_info))
    app_type = models.Configuration.app_type_choices
    env_typess = list(models.Configuration.env_type_choices)
    option_typess = models.Configuration.optimize_type_choices
    configcenter_typess = models.Configuration.configcenter_type_choices
    java_versionss = models.Configuration.java_version_choices
    system_releasess = models.Configuration.system_type_choices
    cpu_capacityss = models.Configuration.cpu_capacity_choices
    mem_capacityss = models.Configuration.mem_capacity_choices
    interface_typess = ["http", "dubbo"]
    service_info = {"app_type": app_type, "env_typess": env_typess, "option_typess": option_typess,
                    "configcenter_typess": configcenter_typess, "interface_typess": interface_typess,
                    "system_releasess":system_releasess,"cpu_capacityss":cpu_capacityss,
                    "mem_capacityss":mem_capacityss,"java_versionss":java_versionss}
    print("---------------")
    print(service_info)
    print(env_typess)
    print(type(env_typess))
    return HttpResponse(json.dumps(service_info))


def jenkins(request):
    from serviceinfo import models
    print("dddddddddddddddddddd")
    app_id = request.POST.get("app_id")
    print(app_id)
    res = {"code":None,"id":None,"job_status":None}
    from serviceinfo.jenkins_report import insert_jenkins
    print(33333)
    app_config_obj = models.Configuration.objects.get(id=app_id)
    print("app_config",app_config_obj)
    print(app_config_obj.sername.sername, app_config_obj.get_env_type_display(), app_config_obj.app_type,app_config_obj.group.name,app_config_obj.sername.gitaddr,app_config_obj.sername.git_releases)
    print("jenkins,jenkins!")
    jenkins_statuss = insert_jenkins(app_config_obj.sername.sername, app_config_obj.get_env_type_display(), app_config_obj.app_type,app_config_obj.group.name,app_config_obj.sername.gitaddr,app_config_obj.sername.git_releases)
    print("ssssss",jenkins_statuss)
    if jenkins_statuss["status"] == 200 or jenkins_statuss["status"] == 500:
        # models.Configuration.objects.filter(id=app_id).update(jenkens_status=1)
        app_config_obj.jenkens_status = 1
        app_config_obj.save()
        res["code"] = 200
        res["id"] = app_id
        res["job_status"] = app_config_obj.get_jenkens_status_display()
    else:
        # models.Configuration.objects.filter(sername__sername=app_config_obj.sername.sername, env_type=app_config_obj.env_type).update(jenkens_status=2)
        app_config_obj.jenkens_status = 2
        app_config_obj.save()
        res["code"] = 500
        res["id"] = app_id
        res["job_status"] = app_config_obj.get_jenkens_status_display()
    print("kkkk",res)
    return HttpResponse(json.dumps(res))

def jenkins_del(request):

    print("jenkins del 99999")
    app_id = request.POST.get("app_id")
    app_obj = models.Configuration.objects.filter(id=app_id)[0]
    print(app_obj)
    # 删除jenkins工作
    # print("jenkinsdel,89797!")
    # print(app_obj)
    # print("jenkinsdel,jenkinsdel!")
    from serviceinfo.jenkins_report import jenkins_job_del
    # print("zzzzz")
    res = jenkins_job_del(app_obj.sername.sername, app_obj.get_env_type_display(),app_obj.group.name)
    if res["status"] == 200:
        app_obj.jenkens_status = 3
    else:
        app_obj.jenkens_status = 1
    app_obj.save()
    print(res)
    return HttpResponse(json.dumps(res))

def saveapp(request):
    return HttpResponse("ok")


def copy_appinfo(request):

    res = {"status":1,"app_names":list()}
    flag = False
    id=request.session.get("user_id")
    user=rbac_model.User.objects.filter(id=id).first()
    print("22222222222")
    print(user.department.id)
    print(request.session["menu_permission_list"])
    per=Per(request.actions)
    if request.method == "POST":
        ids = request.POST.get("app_ids")
        env_id = request.POST.get("env_id")
        group = request.POST.get("group")
        print(ids)
        print(env_id)
        print(group)
        ids = json.loads(ids)

        for id in ids:
            ssss = models.Configuration.objects.filter(id=id)[0]
            sername = models.ConnService.objects.filter(configuration__id=id)[0].sername

            app_obj = models.Configuration.objects.filter(sername__sername=sername,env_type=int(env_id),group_id=int(group))
            print(app_obj)
            if app_obj:
                print(1111)
                flag = True
                res["app_names"].append(app_obj[0].sername.sername)
            else:
                print(2222)
                print(models.Configuration.objects.filter(id=int(id)).values()[0])
                print(type(models.Configuration.objects.filter(id=int(id)).values()[0]))
                app_dict = models.Configuration.objects.filter(id=int(id)).values()[0]
                app_dict["env_type"] = int(env_id)
                app_dict["group_id"] = int(group)
                app_dict["related_user_id"] = user.id
                app_dict.pop("id")
                app_dict.pop("jenkens_status")
                app_dict.pop("ingress_type")
                app_dict.pop("createDate")
                app_dict.pop("updateDate")

                serviceaa_obj = models.Configuration.objects.create(**app_dict)
                if serviceaa_obj.configcenter_type == 1:
                    serviceaa_obj.configcenter_addr = serviceaa_obj.get_env_type_display()
                else:
                    serviceaa_obj.configcenter_addr = app_dict["configcenter_addr"].replace(ssss.get_env_type_display(),serviceaa_obj.get_env_type_display())
                serviceaa_obj.save()
        if flag:
            res["status"] = 500
            print(res)
        else:
            res["status"] = 200
    else:
        res = {"status": 1}

    return HttpResponse(json.dumps(res))


def add_env(request):
    res = {"status":1}
    env_name = request.POST.get("env_name").strip()

    print(env_name)
    env_obj = models.Group.objects.filter(name=env_name)
    if env_obj:
        res["status"] = 500
    else:
        models.Group.objects.create(name=env_name)
        res["status"] = 200
    return HttpResponse(json.dumps(res))

def envinfo(request):
    res = {"status":1}
    print("vvvvvvvvvvv")
    group_list = list(models.Group.objects.all().values_list())

    env_list = list(models.Configuration.env_type_choices)
    res["group_list"] = group_list
    res["env_list"] = env_list
    print(res)
    return HttpResponse(json.dumps(res))

def httpinfo(request):
    id=request.session.get("user_id")
    user = rbac_model.User.objects.filter(id=id).first()
    print(request.actions)
    per = Per(request.actions)

    print("rrrr",request.path)

    # 从URL取参数
    page_num = request.GET.get("page")
    # print(page_num, type(page_num))
    appname = request.GET.get("appname")
    group = request.GET.get("group")
    env = request.GET.get("env")
    if env:
        env = int(env)
    else:
        env = 1

    if appname == None:
        appname = ''
    else:
        appname = appname.strip()

    if group:
        group = int(group)
    else:
        group = 1
    print("app",appname)
    print("app",page_num)
    print("app",group)

    envs = models.Configuration.env_type_choices
    # envs = [('dev',),('qa',),('online',),('all',)]
    envs = list(envs)
    envs.append((4, 'all'))
    print("eeee",envs)
    groups = list(models.Group.objects.all().values_list())
    groups.append((100,'all'))
    print("ggg",groups)
    if env == 4 and group == 100:
        # 总数据是多少
        total_count = models.Configuration.objects.filter(interface_type__contains="http",sername__sername__contains=appname).all().count()

        from utils.mypage import Page
        page_obj = Page(page_num, total_count, per_page=9,
                        url_prefix="/serviceinfo/httpinfo/?env={}&appname={}&group={}&".format(env,appname,group), max_page=9, )
        ret = models.Configuration.objects.filter(interface_type__contains="http",sername__sername__contains=appname).all()[page_obj.start:page_obj.end]
        page_html = page_obj.page_html()
    elif env == 4 and group != 100:
        # 总数据是多少
        total_count = models.Configuration.objects.filter(interface_type__contains="http",sername__sername__contains=appname,group_id=group).all().count()

        from utils.mypage import Page
        page_obj = Page(page_num, total_count, per_page=9,
                        url_prefix="/serviceinfo/httpinfo/?env={}&appname={}&group={}&".format(env,appname,group), max_page=9, )
        ret = models.Configuration.objects.filter(interface_type__contains="http",sername__sername__contains=appname,group_id=group).all()[page_obj.start:page_obj.end]
        page_html = page_obj.page_html()
    elif env != 4 and group == 100:
        # 总数据是多少
        total_count = models.Configuration.objects.filter(interface_type__contains="http",sername__sername__contains=appname,env_type=env).all().count()

        from utils.mypage import Page
        page_obj = Page(page_num, total_count, per_page=9,
                        url_prefix="/serviceinfo/httpinfo/?env={}&appname={}&group={}&".format(env,appname,group), max_page=9, )
        ret = models.Configuration.objects.filter(interface_type__contains="http",sername__sername__contains=appname,env_type=env).all()[page_obj.start:page_obj.end]
        print(ret)
        page_html = page_obj.page_html()
    else:
        # 总数据是多少
        total_count = models.Configuration.objects.filter(interface_type__contains="http",sername__sername__contains=appname,env_type=env,group_id=group).all().count()

        from utils.mypage import Page
        page_obj = Page(page_num, total_count, per_page=9,
                        url_prefix="/serviceinfo/httpinfo/?env={}&appname={}&group={}&".format(env,appname,group), max_page=9, )
        ret = models.Configuration.objects.filter(interface_type__contains="http",sername__sername__contains=appname,env_type=env,group_id=group).all()[page_obj.start:page_obj.end]
        print(ret)
        page_html = page_obj.page_html()

    return render(request,"httpinfo.html",{"server_list":ret,"page_html":page_html,"user":user,"per":per,"appname":appname,"envs":envs,"env":env,"group":group,"groups":groups})

def http_detail(request):
    res = {"status":500,"app_info":None}
    if request.method == "POST":
        pro_id = request.POST.get("pro_id")
        print(pro_id)
        try:
            app_obj = models.Configuration.objects.get(id=pro_id)
            res["app_info"] = {"proj_id":app_obj.id,"domain":app_obj.hostname,"port":app_obj.port,"request_path":app_obj.request_path,"service_path":app_obj.service_path,"personalize":app_obj.personalize,"persontext":app_obj.persontext}
            res["status"] = 200
        except Exception as e:
            res["status"] = 500

    return HttpResponse(json.dumps(res))


def update_http(request,id):
    print(1212121212)
    res = {"status":500}
    pro_id = request.POST.get("proj_id")
    hostname = request.POST.get("hostname")
    port = request.POST.get("port")
    request_path = request.POST.get("request_path").strip()
    service_path = request.POST.get("service_path")

    personalize = request.POST.get("personalize")
    persontext = request.POST.get("personalizetext")

    if int(personalize) == 1:
        persontext = persontext.strip()
    else:
        persontext = None

    if service_path:
        service_path = service_path.strip()
    else:
        service_path = request_path

    hostnames = [sm for sm in hostname.split("\n")]

    print("per",personalize)
    print("per",persontext)

    app_name_set = set()
    # app_path_list = list()
    for hh in hostnames:
        app_path_list = models.Configuration.objects.filter(hostname__contains=hh,request_path=request_path).values("sername__sername","request_path")
        if app_path_list:
            # print(app_path_list)
            app_list = set([app["sername__sername"] for app in app_path_list])
            app_name_set = app_name_set | app_list
            break

    print("setsxeset",app_name_set)
    update_info = {"hostname": hostname, "port": int(port), "request_path": request_path, "service_path": service_path,"personalize":personalize,"persontext":persontext}
    if app_name_set:
        print(5454545454)
        # sm_app = models.Configuration.objects.filter(hostname__contains=hostnames[0])
        res["appname"] = list(app_name_set)[0]
        app_name = models.Configuration.objects.filter(id=pro_id)[0].sername.sername
        print("appname",app_name)
        print("ressss",res)
        if res["appname"] == app_name:
            try:
                models.Configuration.objects.filter(id=pro_id).update(**update_info)
                res["status"] = 200
            except Exception as e:
                res["status"] = 500
        else:
            print(777777)
            res["status"] = 400
    else:
        print(45454545)
        # print(update_info)
        try:
            models.Configuration.objects.filter(id=pro_id).update(**update_info)
            res["status"] = 200
        except Exception as e:
            res["status"] = 500
    return HttpResponse(json.dumps(res))


import requests
import os
import subprocess
import paramiko
import time

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

def ingress_create(domain_name,appname,group,env,request_path,personalize,persontext):
    print("base",BASE_DIR)
    nginx_location_path = "%s/nginx/service_location_conf/%s-%s/%s"%(BASE_DIR,group,env,domain_name)
    if os.path.exists(nginx_location_path):
        print("exists!")
    else:
        print("创建文件")
        os.makedirs(nginx_location_path)

    if not request_path.strip().endswith('/'):
        request_path = request_path.strip() + '/'

    with open('%s/%s.conf'%(nginx_location_path,appname), 'w') as f:
        f.write("location %s {\n"%request_path)
        if personalize == 1:
            for l in persontext.split("\n"):
                if l:
                    f.write("\t%s\n" % l.strip())
        f.write("\t%s;\n" % "proxy_pass http://ingress")
        f.write("}")
    # if personalize == 1:
    #     with open("%s/nginx/service_location_conf/%s-%s/%s/%s.conf" % (BASE_DIR, group, env, domain_name, appname),
    #               mode="w", encoding="utf-8") as f:
    #         f.write(persontmpp.replace("qding_appname", request_path).replace("personalizetextss",persontext.replace("\n","\n    ")))
    # else:
    #     with open("%s/nginx/service_location_conf/%s-%s/%s/%s.conf"%(BASE_DIR,group,env,domain_name,appname),mode="w",encoding="utf-8") as f:
    #         f.write(tmpp.replace("qding_appname",request_path))

# ingress_create("qapstar2.qdingnet.com","qdp-polestar-web")

def sub_ingress_conf(appname):
    aa = "cd %s/nginx/ && git add . && git commit -m '%s' && git push -u origin master"%(BASE_DIR,appname+"_"+str(int(time.time()*100000)))
    obj = subprocess.Popen(aa,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
    print(obj.stdout.read())
    print(666666666)
    return 1


def rsyn_nginx_git(ip,port,pukey,addr,commands):
    pkey = paramiko.RSAKey.from_private_key_file(pukey)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect(hostname=ip, port=port, username='root', pkey=pkey)

    stdin, stdout, stderr = ssh.exec_command('cd %s && git checkout . && git pull origin master'%addr)
    print(stdout.read().decode())
    # ssh.close()
    stdin, stdout, stderr = ssh.exec_command('%s -s reload'%commands)
    # print(stderr.read().decode())
    res = stderr.read().decode().split("\n")[0]
    ssh.close()
    print(res)
    if "ok" in res:
        return 1
    else:
        return None

# rsyn_nginx_git("10.37.253.30",22,"id_rsa_32","/usr/local/nginx/conf/nginx-git")

from config import setting
def create_ingress_sync_conf(domain_list,sername,group,env,request_path,personalize,persontext):
    for dd in domain_list:
        print("start create dir")
        ingress_create(dd,sername,group,env,request_path,personalize,persontext)
    print("===============================")
    sub_ingress_conf(sername)
    print(33333)
    for pp in setting.NGINX_CONF:
        rsyn_nginx_git(pp["ip"], pp["port"], "id_rsa_32", pp["addr"],pp['command'])

def del_ingress_dir(domain_name,group,env,appname):
    aa = "cd %s/nginx/ && git rm -rf service_location_conf/%s-%s/%s/%s.conf" % (BASE_DIR,group,env,domain_name,appname)
    obj = subprocess.Popen(aa, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    print(obj.stdout.read())
    return 1

def del_ingress_sync_conf(domain_list,appname,group,env):
    for dd in domain_list:
        del_ingress_dir(dd,group,env,appname)
    aa = "cd %s/nginx/ && git add . && git commit -m '%s' && git push -u origin master"%(BASE_DIR,appname+"_"+str(int(time.time()*100000)))
    obj = subprocess.Popen(aa,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
    print(obj.stdout.read())
    for pp in setting.NGINX_CONF:
        rsyn_nginx_git(pp["ip"], pp["port"], "id_rsa_32", pp["addr"],pp["command"])
    return 1

def no_domain(request):
    res = {"status":500}
    proj_id = request.POST.get("proj_id")
    app_obj = models.Configuration.objects.get(id=proj_id)
    domain = app_obj.hostname.split("\n")
    print(domain)
    domain_list = []
    for dd in domain:
        if dd:
            domain_list.append(dd)

    data2 = {
        "group": app_obj.group.name,
        "env": app_obj.get_env_type_display(),
        "appname": app_obj.sername.sername,
    }
    print("data2data2",data2)
    # app_info = {"port":None,"request_path":"/","service_path":"/","hostname":None}
    # models.Configuration.objects.filter(id=proj_id).update(**app_info)
    # print(555,app_obj)
    ret = requests.post("http://10.37.253.241:8000/k8s/ingress/delete/", data2)
    print("ret",ret.text)
    print("ret",type(ret.text))
    ret = json.loads(ret.text)

    if ret["code"] == 200:
        del_ingress_sync_conf(domain_list,app_obj.sername.sername,app_obj.group.name,app_obj.get_env_type_display())
        models.Configuration.objects.filter(id=proj_id).update(ingress_type=3)
        res["status"] = 200
    else:
        res["status"] = 500
        models.Configuration.objects.filter(id=proj_id).update(ingress_type=1)

    return HttpResponse(json.dumps(res))

def ingress(request):
    print("innngressss")
    res = {"status":500}
    proj_id = request.POST.get("proj_id")
    print(proj_id)
    app_obj = models.Configuration.objects.get(id=proj_id)
    domain = app_obj.hostname.split("\n")
    print(domain)
    domain_list = []
    for dd in domain:
        if dd:
            domain_list.append(dd)
    #['devboss.qdingnet.com', 'devbos2.qdingnet.com', 'devbos4.qdingnet.com']
    # print(domain_list)

    # editor houkailong 解决ingress 字符串空格问题
    group = app_obj.group.name.strip()
    env = app_obj.get_env_type_display()
    appname = app_obj.sername.sername.strip()
    request_path = app_obj.request_path.strip()
    app_path = app_obj.service_path.strip()

    data1 = {
        "group": group,
        "env": env,
        "appname": appname,
        "domain": domain_list,
        "request_path": request_path,
        "app_path": app_path,
        "app_port": app_obj.port
    }
    print("data1",data1)
    try:
        ret = requests.post("http://10.37.253.241:8000/k8s/ingress/deploy/", data1)
        print(ret.text)
        # print(type(ret.text))
        ret = json.loads(ret.text)
        if ret["code"] == 200:
            app_obj.ingress_type = 1
            # print("1111111111111111111")
            try:
                create_ingress_sync_conf(domain_list,app_obj.sername.sername,app_obj.group.name,app_obj.get_env_type_display(),app_obj.request_path,app_obj.personalize,app_obj.persontext)

                # create_ingress_sync_conf(domain_list, appname, group, env, request_path)

                print(456788)
                res["status"] = 200
            except Exception as e:
                # print(22222222222222)
                res["status"] = 500
        else:
            app_obj.ingress_type =2
            res["status"] = 500
        app_obj.save()
    except Exception as e:
        app_obj.ingress_type = 2
        app_obj.save()
        res["status"] = 500
    return HttpResponse(json.dumps(res))